from wx import Frame,Panel,FilePickerCtrl,TextCtrl,Button,BoxSizer,StaticText,MessageBox,App
from wx import FLP_USE_TEXTCTRL,EVT_BUTTON,VERTICAL,ALL,EXPAND,OK,ALIGN_CENTER_HORIZONTAL,ICON_ERROR,ICON_INFORMATION
from PyPDF2 import PdfReader,PdfWriter

class MyFrame(Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(400, 350))

        self.panel = Panel(self)

        self.file_picker = FilePickerCtrl(self.panel, style=FLP_USE_TEXTCTRL)
        self.page_input = TextCtrl(self.panel)
        self.output_filename_input = TextCtrl(self.panel, value='output')
        self.start_button = Button(self.panel, label='开始执行')

        self.start_button.Bind(EVT_BUTTON, self.on_start_button_clicked)

        sizer = BoxSizer(VERTICAL)
        sizer.Add(StaticText(self.panel, label='选择PDF文件：'), flag=ALL, border=10)
        sizer.Add(self.file_picker, flag=EXPAND|ALL, border=10)
        sizer.Add(StaticText(self.panel, label='输入页码：'), flag=ALL, border=10)
        sizer.Add(self.page_input, flag=EXPAND|ALL, border=10)
        sizer.Add(StaticText(self.panel, label='输出文件名：'), flag=ALL, border=10)
        sizer.Add(self.output_filename_input, flag=EXPAND|ALL, border=10)
        sizer.Add(self.start_button, flag=ALL|ALIGN_CENTER_HORIZONTAL, border=10)

        self.panel.SetSizer(sizer)
        self.Show()

    def on_start_button_clicked(self, event):
        source_file = self.file_picker.GetPath()
        page_numbers_str = self.page_input.GetValue()
        output_filename = self.output_filename_input.GetValue()

        if not source_file:
            MessageBox('请选择有效的PDF文件', '错误', OK | ICON_ERROR)
            return

        if not page_numbers_str:
            MessageBox('请输入要提取的页码', '错误', OK | ICON_ERROR)
            return


        try:
            page_numbers = self.parse_page_numbers(page_numbers_str)
            if page_numbers == []:
                MessageBox('请查正要提取的页码', '错误', OK | ICON_ERROR)
                return
            print(page_numbers)
        except ValueError:
            MessageBox('无效的页码输入', '错误', OK | ICON_ERROR)
            return

        output_file = output_filename + '.pdf'

        try:
            extract_pages(source_file, output_file, page_numbers)

            MessageBox('提取完成', '提示', OK | ICON_INFORMATION)
        except:
            MessageBox('提取页面时发生错误', '错误', OK | ICON_ERROR)


    def parse_page_numbers(self, page_numbers_str):
        page_numbers = []
        ranges = page_numbers_str.replace(' ', '').split(',')

        for r in ranges:
            if '-' in r:
                start, end = r.split('-')
                page_numbers.extend(range(int(start), int(end) + 1))
            else:
                page_numbers.append(int(r))

        return page_numbers

def extract_pages(input_path, output_path, pages):
    with open(input_path, 'rb') as input_file:
        reader = PdfReader(input_file)
        writer = PdfWriter()

        for page_number in pages:
            # PyPDF2的页面索引从0开始，而实际页码从1开始，所以需要进行转换
            page_index = page_number - 1
            if page_index >= 0 and page_index < len(reader.pages):
                page = reader.pages[page_index]
                writer.add_page(page)

        with open(output_path, 'wb') as output_file:
            writer.write(output_file)

app = App()
frame = MyFrame(None, title='PDF页面提取工具')
app.MainLoop()